const WebSocketServer = require('ws').Server;

const XINGTIAO_STR = JSON.stringify({'e':'h'})

class SocketServer{
    constructor(cfg){
        this.events = {};
        this.clients = [];
        this.wss = new WebSocketServer(cfg);
        console.log('SocketServer is listener:',cfg.port);
        this.wss.on('connection',this.onNewClient.bind(this))
        setInterval(this.onHeadLine.bind(this),500);
    }

    onHeadLine(){
        // this.wss.
        try{
            for(let i=0; i<this.clients.length; i++){
                // this.send(this.clients[i],{e:'h'})
                this.clients[i].send(XINGTIAO_STR);
            }
        }catch(e){
            console.log('onHeadLine:',e.message);
        }

    }
    onNewClient(ws){
        ws.on('message',this.onMessage.bind(this,ws))
        ws.on('close', this.onClose.bind(this,ws));
        this.clients.push(ws);
    }

    onMessage(ws,message){
        try{
            var d = JSON.parse(message);
            if(d){
                this.dispatch(d.e,ws,d)
            }
        }catch(e){

        }
    }
    dispatch(d,ws,v){
        if(this.events[d]){
            try{
                for(var i=0; i<this.events[d].length; i++){
                    this.events[d][i](ws,v);
                }
            }catch(e){
                console.log('socket server dispatch ',v,e.message)
            }
        } else {
            console.log('未处理的消息:',d,v);
        }
    }
    onClose(ws){
        console.log('onClose',ws._userid);
        var idx = this.clients.findIndex(item=>{return item == ws});
        this.clients.splice(idx,1);
        this.dispatch('close',ws);
    }
    addEvent(key,cb){
        if(this.events[key]){
            this.events[key].push(cb);
        } else {
            this.events[key] = [cb];
        }
    }

    send(ws,str){
        if(typeof(str) == 'object'){
            str = JSON.stringify(str)
        }
        ws.send(str);
    }

}
module.exports = SocketServer